//
//  SettingViewController.m
//  moon
//
//  Created by beyself on 16/6/14.
//  Copyright © 2016年 beyself. All rights reserved.
//
#import "Utils.h"
#import "SettingViewController.h"
#import "UIImageView+AFNetworking.h"
#import "AFHTTPSessionManager.h"
#import "AboutViewController.h"
#import "ModifyPwdViewController.h"
#import "ProfileViewController.h"
#import "UserSpaceViewController.h"
#import "MemberCenterViewController.h"
#import "MateInfoViewController.h"

@interface SettingViewController ()<UIActionSheetDelegate>

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSDictionary* item = APPDELEGATE.mMemberInfo;

    UIView* top = [[UIView alloc] init];
    top.frame = CGRectMake(0, 0, SCREEN_WIDTH, 20);
    top.backgroundColor = BLUE;
    [self.view addSubview:top];
    
    UIScrollView* scrollview = [[UIScrollView alloc] init];
    scrollview.frame = CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT);
    scrollview.showsVerticalScrollIndicator = NO;
    [self.view addSubview:scrollview];
    
    UIView* head = [[UIView alloc] init];
    head.backgroundColor = BLUE;
    [scrollview addSubview:head];
    /*
    int yPos = 0;
    UILabel* label = [[UILabel alloc] init];
    label.frame = CGRectMake(10, 0, SCREEN_WIDTH - 20, 44);
    label.font = FONT_15;
    label.textColor = WHITE;
    label.textAlignment = NSTextAlignmentCenter;
    label.text = [NSString stringWithFormat:@"%@(%@)",item[@"username"],item[@"telephone"]];
    [head addSubview:label];
    */
    /*
    NSMutableString* str = [[NSMutableString alloc] init];
    
    BOOL isteacher = NO
    NSArray* child = item[@"children"];
    NSArray* classes = item[@"classes"];
    for(NSDictionary* dic in classes)
    {
        if(str.length) [str appendString:@"\n"];

        if([dic[@"is_teacher"] intValue] > 0) [str appendString:dic[@"identitylabel"]];
        BOOL isAdd = NO;
        for(NSDictionary* one in child)
        {
            if([[dic[@"id"] description] isEqualToString:[one[@"class_id"] description]])
            {
                if([dic[@"is_teacher"] intValue] > 0 || isAdd) [str appendString:@","];
                [str appendString:one[@"name"]];
                [str appendString:one[@"identity"]];
                isAdd = YES;
            }
        }
        
        
        [str appendString:@","];
        [str appendString:dic[@"school_name"]];
        NSString* className = dic[@"class_alias"];
        if([Utils isStringNullOrEmpty:className]) className = dic[@"class_name"];
        [str appendString:className];
    }*/
    
    BOOL isteacher = NO;
    NSArray* child = item[@"children"];
    NSArray* classes = item[@"classes"];
    for(NSDictionary* dic in classes)
    {
        if([dic[@"is_teacher"] intValue] > 0)
        {
            isteacher = YES;
            break;
        }
    }

    
    int yPos = 10;
    UILabel* label = [[UILabel alloc] init];
    label.font = FONT_12;
    label.text = item[@"username"];
    label.tag = 3000;
//    label.textAlignment = NSTextAlignmentCenter;
    label.lineBreakMode = NSLineBreakByCharWrapping;
    label.numberOfLines = 0;
    label.textColor = WHITE;
    label.frame = CGRectMake(74, 0, SCREEN_WIDTH - 84, 74);
    [head addSubview:label];
    
    
    UIImageView* imageview = [[UIImageView alloc] init];
    imageview.frame = CGRectMake(10, 10, 54, 54);
    imageview.tag = 2000;
    imageview.contentMode = UIViewContentModeScaleAspectFill;
    imageview.layer.cornerRadius = 27;
    imageview.layer.masksToBounds = YES;
    if(isteacher)
        [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_URL,item[@"avatar_path"]]]
                  placeholderImage:[UIImage imageNamed:@"ic_teacher"]];
    else
        [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_URL,item[@"avatar_path"]]]
                  placeholderImage:[UIImage imageNamed:@"ic_family"]];
    [head addSubview:imageview];
    
    UIControl* control = [[UIControl alloc] init];
    control.frame = CGRectMake(10, 10, 54, 54);
    [control addTarget:self action:@selector(chooseImage) forControlEvents:UIControlEventTouchUpInside];
    [scrollview addSubview:control];

    
    yPos += 74;
    head.frame = CGRectMake(0, 0, SCREEN_WIDTH, 74);
    
    for(int i = -1; i < 7; i++)
    {
        UIButton* button  = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 2100 + i;
        button.frame = CGRectMake(0, yPos, SCREEN_WIDTH, 48);
        button.titleLabel.font = FONT_15;
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button setTitleColor:BLACK forState:UIControlStateNormal];
        [button setBackgroundImage:[Utils imageFromColor:WHITE] forState:UIControlStateNormal];
        [button setBackgroundImage:[Utils imageFromColor:LINE] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        if(i == -1)
        {
            [button setTitle:@"详细信息" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"ic_my"] forState:UIControlStateNormal];
            yPos += 48;
        }
        else if(i == 0)
        {
            [button setTitle:@"修改密码" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"icon_personal"] forState:UIControlStateNormal];
            yPos += 48;
        }
        else if(i == 1)
        {
            [button setTitle:@"我的空间" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"icon_space"] forState:UIControlStateNormal];
            yPos += 48;
        }
        else if(i == 2)
        {
            [button setTitle:@"会员中心" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"icon_member"] forState:UIControlStateNormal];
            yPos += 58;
        }
        else if(i == 5)
        {
            [button setTitle:@"当前版本" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"icon_ver"] forState:UIControlStateNormal];
            yPos += 58;
        }
        else if(i == 4)
        {
            [button setTitle:@"关于我们" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"icon_about"] forState:UIControlStateNormal];
            yPos += 48;
        }
        else if(i == 3)
        {
            [button setTitle:@"系统设置" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"icon_setting"] forState:UIControlStateNormal];
            yPos += 48;
        }
        else if(i == 6)
        {
            [button setTitle:@"退出登录" forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"ic_logout"] forState:UIControlStateNormal];
            yPos += 58;
        }
        
        if(i != 5)
        {
            UIButton* arrow = [UIButton buttonWithType:UIButtonTypeCustom];
            arrow.frame = CGRectMake(SCREEN_WIDTH - 48, 0, 48, 48);
            [arrow setImage:[UIImage imageNamed:@"ic_arrow"] forState:UIControlStateNormal];
            [button addSubview:arrow];
        }
        else
        {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            
            UILabel* label = [[UILabel alloc] init];
            label.frame = CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2 - 10, 48);
            label.font = FONT_12;
            label.textColor = GRAY;
            label.textAlignment = NSTextAlignmentRight;
            label.text = [NSString stringWithFormat:@"V%@",app_Version];
            [button addSubview:label];
        }
        
        CALayer* layer = [[CALayer alloc] init];
        layer.frame = CGRectMake(0, 47.5, SCREEN_WIDTH, .5);
        layer.backgroundColor = BG.CGColor;
        [button.layer addSublayer:layer];
        
        [scrollview addSubview:button];
    }
    /*
    yPos += 20;
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, yPos, SCREEN_WIDTH - 40, 48);
    button.layer.cornerRadius = 5;
    button.layer.masksToBounds = YES;
    button.titleLabel.font = FONT_15;
    [button setBackgroundImage:[Utils imageFromColor:RED] forState:UIControlStateNormal];
    [button setBackgroundImage:[Utils imageFromColor:LINE] forState:UIControlStateHighlighted];
    [button setTitle:@"退出" forState:UIControlStateNormal];
    [button setTitleColor:WHITE forState:UIControlStateNormal];
    [button addTarget:self action:@selector(showQuery) forControlEvents:UIControlEventTouchUpInside];
    [scrollview addSubview:button];
    
    yPos += 58;*/
    scrollview.contentSize = CGSizeMake(SCREEN_WIDTH, yPos);
}

- (void) showQuery
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"确定退出该账号?"
                                                   delegate:self
                                          cancelButtonTitle:@"返回" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.cancelButtonIndex != buttonIndex)
    {
        NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
        [param setObject:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
        [param setObject:@" " forKey:@"ios_token"];
        [Utils sendHttpPost:param method:@"member_token" controller:self flag:1];
    }
}

- (void) buttonClick:(UIButton*)btn
{
    if(btn.tag == 2104)
    {
        AboutViewController* subview = [[AboutViewController alloc] init];
        subview.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:subview animated:YES];
    }
    if(btn.tag == 2102)
    {
        MemberCenterViewController* subview = [[MemberCenterViewController alloc] init];
        subview.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:subview animated:YES];
    }
    else if(btn.tag == 2100)
    {
        NSString* name = APPDELEGATE.mMemberInfo[@"username"];
        
        ModifyPwdViewController* subview = [[ModifyPwdViewController alloc] init];
        subview.hidesBottomBarWhenPushed = YES;
        subview.name = name;
        [self.navigationController pushViewController:subview animated:YES];
    }
    else if(btn.tag == 2099)
    {
        MateInfoViewController* subview = [[MateInfoViewController alloc] init];
        subview.mUserId = [APPDELEGATE.mMemberInfo[@"id"] description];
        subview.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:subview animated:YES];
    }
    else if(btn.tag == 2101)
    {
        UserSpaceViewController* subview = [[UserSpaceViewController alloc] init];
        subview.hidesBottomBarWhenPushed = YES;
        subview.mUserId = [APPDELEGATE.mMemberInfo[@"id"] description];
        [self.navigationController pushViewController:subview animated:YES];
    }
    else if(btn.tag == 2103)
    {
        ProfileViewController* subview = [[ProfileViewController alloc] init];
        subview.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:subview animated:YES];
    }
    else if(btn.tag == 2106)
    {
        [self showQuery];
    }
}

- (void) chooseImage
{
    UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:@"选择图片"
                                                       delegate:self
                                              cancelButtonTitle:@"返回"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"从相册获取",@"拍照", nil];
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        UIImagePickerController* imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = NO;
        
        [self presentModalViewController:imagePicker animated:YES];
    }
    else if(buttonIndex == 1)
    {
        UIImagePickerController* imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = NO;
        
        [self presentModalViewController:imagePicker animated:YES];
    }
}

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    
    UIImage *bigImage = [Utils imageCompressForWidth:image targetWidth:240];
    [self sendHttpImage:bigImage];
    
    [self dismissModalViewControllerAnimated:YES];
}

- (void) sendHttpImage:(UIImage*)image
{
    NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
    [param setValue:APPDELEGATE.mMemberInfo[@"id"] forKey:@"id"];
    [param setValue:[Utils md5:[NSString stringWithFormat:@"%@ylbb",@"update_profile"]] forKey:@"sec"];
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:[NSString stringWithFormat:@"http://120.27.129.233/ylbb/api/%@",@"update_profile"]
       parameters:param constructingBodyWithBlock:^(id  _Nonnull formData) {
           
           NSData *imageData = UIImageJPEGRepresentation(image, 0.3);
           [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar" mimeType:@"image/jpeg"];
       } progress:^(NSProgress * _Nonnull uploadProgress) {
           // 这里可以获取到目前的数据请求的进度
           
       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
           if([dic[@"statusCode"] intValue] == 0)
           {
               ((UIImageView*)[self.view viewWithTag:2000]).image = image;
               [self loginBtn];
           }
           else
           {
               
           }
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           [self showAllTextDialog:@"网络状况不佳，请稍后重试..."];
       }];
}

- (void) loginBtn
{
    NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
    [param setObject:[Utils readDefaultUser:@"username"] forKey:@"phonenumber"];
    [param setObject:[Utils readDefaultUser:@"password"] forKey:@"password"];
    [Utils sendHttpPost:param method:@"member_login" controller:self flag:0];
}

- (void) httpCallback:(NSDictionary*)data flag:(int)flag
{
    if(flag == 0)
    {
        [Utils saveCustomObject:data[@"member"] key:LOGIN_INFO];
        [APPDELEGATE.mMemberInfo setDictionary:data[@"member"]];
    }
    else if(flag == 1)
    {
        [Utils saveDefaultUser:@"" key:@"username"];
        [Utils saveCustomObject:@"" key:LOGIN_INFO];
/*        [Utils saveCustomObject:@"" key:@"cache_0"];
        [Utils saveCustomObject:@"" key:@"cache_1"];
        [Utils saveCustomObject:@"" key:@"cache_2"];
        [Utils saveCustomObject:@"" key:@"cache_3"];*/
        [APPDELEGATE.mMemberInfo removeAllObjects];
        [APPDELEGATE showMainView];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void) viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES];
    
    NSDictionary* item = APPDELEGATE.mMemberInfo;
    NSMutableString* str = [[NSMutableString alloc] init];
    
    NSArray* child = item[@"children"];
    NSArray* classes = item[@"classes"];
    for(NSDictionary* dic in classes)
    {
        if(str.length) [str appendString:@"\n"];
        
        if([dic[@"is_teacher"] intValue] > 0) [str appendString:dic[@"identitylabel"]];
        BOOL isAdd = NO;
        for(NSDictionary* one in child)
        {
            if([[dic[@"id"] description] isEqualToString:[one[@"class_id"] description]])
            {
                if([dic[@"is_teacher"] intValue] > 0 || isAdd) [str appendString:@","];
                [str appendString:one[@"name"]];
                [str appendString:one[@"identity"]];
                isAdd = YES;
            }
        }
        
        
        [str appendString:@","];
        [str appendString:dic[@"school_name"]];
        NSString* className = dic[@"class_alias"];
        if([Utils isStringNullOrEmpty:className]) className = dic[@"class_name"];
        [str appendString:className];
    }
    ((UILabel*)[self.view viewWithTag:3000]).text = item[@"username"];
}

- (void) viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO];
}

@end
